package com.miguo.framework.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 名称：ScaleImageView.java
 * 
 * 描述：根据宽度或高度设置图像尺寸，如果未设置取决于图像尺寸
 */
public class ScaleImageView extends ImageView {

	/** 当前的bitmap. */
	private Bitmap currentBitmap;

	/** The image width. */
	private int imageWidth;

	/** The image height. */
	private int imageHeight;

	/**
	 * 构造方法.
	 * 
	 * @param context
	 *            the context
	 */
	public ScaleImageView(Context context) {
		super(context);
		init();
	}

	/**
	 * 构造方法.
	 * 
	 * @param context
	 *            the context
	 * @param attrs
	 *            the attrs
	 * @param defStyle
	 *            the def style
	 */
	public ScaleImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	/**
	 * 构造方法.
	 * 
	 * @param context
	 *            the context
	 * @param attrs
	 *            the attrs
	 */
	public ScaleImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	/**
	 * 初始化图片缩放类型.
	 */
	private void init() {
		this.setScaleType(ScaleType.CENTER_INSIDE);
	}

	/**
	 * 回收.
	 */
	public void recycle() {
		setImageBitmap(null);
		if ((this.currentBitmap == null) || (this.currentBitmap.isRecycled()))
			return;
		this.currentBitmap.recycle();
		this.currentBitmap = null;
	}

	/**
	 * 描述：设置图片Bitmap
	 */
	@Override
	public void setImageBitmap(Bitmap bm) {
		currentBitmap = bm;
		super.setImageBitmap(currentBitmap);
	}

	/**
	 * 描述：设置图片Drawable
	 */
	@Override
	public void setImageDrawable(Drawable d) {
		super.setImageDrawable(d);
	}

	/**
	 * 描述：设置图片资源
	 */
	@Override
	public void setImageResource(int id) {
		super.setImageResource(id);
	}

	/**
	 * 描述：onMeasure
	 * 
	 * @see ImageView#onMeasure(int, int)
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

		if (imageWidth == 0) {
			// 按图片大小
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
			return;
		} else {
			this.setScaleType(ScaleType.CENTER_CROP);
			setMeasuredDimension(imageWidth, imageHeight);
		}
	}

	/**
	 * 设置View的宽度.
	 * 
	 * @param w
	 *            the new image width
	 */
	public void setImageWidth(int w) {
		imageWidth = w;
	}

	/**
	 * 设置View的高度.
	 * 
	 * @param h
	 *            the new image height
	 */
	public void setImageHeight(int h) {
		imageHeight = h;
	}

}
